package cn.exrick.manager.service.impl;

import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.manager.mapper.TbNewsMapper;
import cn.exrick.manager.pojo.TbNews;
import cn.exrick.manager.pojo.TbNewsExample;
import cn.exrick.manager.service.NewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private TbNewsMapper tbNewsMapper;

    @Override
    public TbNews getNewsById(Long id) {
        return tbNewsMapper.getNewsById(id);
    }

    @Override
    public void addNews(TbNews tbNews) {
        tbNews.setCreateTime(new Date());
        tbNews.setUpdateTime(new Date());
        tbNewsMapper.insert(tbNews);
    }

    @Override
    public void updateNews(TbNews tbNews) {
        tbNews.setUpdateTime(new Date());
        tbNewsMapper.updateByPrimaryKeySelective(tbNews);
    }

    @Override
    public void deleteNews(List<Long> ids) {
        TbNewsExample example = new TbNewsExample();
        TbNewsExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        tbNewsMapper.deleteByExample(example);
    }

    @Override
    public void topNews(Long id) {
        //先取消原来置顶的
        tbNewsMapper.cancelTop();
        TbNews tbNews = new TbNews();
        tbNews.setIsTop(true);
        tbNews.setId(id);
        tbNewsMapper.updateByPrimaryKeySelective(tbNews);
    }

    @Override
    public void cancelTopNews(Long id) {
        TbNews tbNews = new TbNews();
        tbNews.setIsTop(false);
        tbNews.setId(id);
        tbNewsMapper.updateByPrimaryKeySelective(tbNews);
    }

    @Override
    public void alterNewsStatus(Long id, Integer status) {
        TbNews tbNews = new TbNews();
        tbNews.setStatus(status);
        tbNews.setId(id);
        tbNewsMapper.updateByPrimaryKeySelective(tbNews);
    }


    @Override
    public DataTablesResult getNewsList(int draw, int start, int length,TbNews tbNews, String orderCol, String orderDir) {
        DataTablesResult result=new DataTablesResult();
        //分页
        PageHelper.startPage(start/length+1,length);
        List<TbNews> tbNewsList = tbNewsMapper.selectByCondition(tbNews,orderCol,orderDir);
        PageInfo<TbNews> pageInfo = new PageInfo<>(tbNewsList);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal((int)pageInfo.getTotal());

        result.setDraw(draw);
        result.setData(tbNewsList);
        return result;
    }
}
